﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace XoLib.CatchException
{

    /// <summary>
    /// Exception Manager
    /// </summary>
    public class ExceptionManager
    {

     private static event UnhandledExceptionEventHandler _bind;

     /// <summary>
     /// Init
     /// </summary>
        public static void CatchAll()
        {
            /*if (System.Diagnostics.Debugger.IsAttached)
                return;*/

           System.AppDomain.CurrentDomain.UnhandledException -= UnhandledExceptionHandler;
           System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;

        }

        /// <summary>
        /// <para>
        /// <param name="evt">UnhandledExceptionEventHandler</param>
        /// </para>
        /// Bind 
        /// </summary>
        public static void Bind(UnhandledExceptionEventHandler evt)
        {
            _bind -= evt;
            _bind += evt;
        }


         private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {

                CLogManager.WriteException((Exception)e.ExceptionObject).Level(1).Where("UnhandledExceptionHandler").Write();

                if (_bind != null)
                    _bind(sender, e);

                ExceptionDialog d = new ExceptionDialog();
                d.ShowDialog();
               
            }
            catch
            {
            }
            finally
            {
                System.Diagnostics.Process.GetCurrentProcess().Kill();
                Application.Exit();
            }

        }

    }
}
